<template>
    <div class="login-container" :class="{ 'dark': isDark }">
        <div class="theme-switch">
            <el-button
                @click="toggleDark()"
                :icon="isDark ? Moon : Sunny"
                circle
                plain
            />
        </div>
        <div class="main">
            
            <el-card class="login-card">
                <div class="title">
                    <h2>闲置物品交易后台</h2>
                    
                </div>
                <el-form
                    ref="loginFormRef"
                    :model="loginForm"
                    :rules="rules"
                    class="login-form"
                >
                    <el-form-item prop="username">
                        <el-input
                            v-model="loginForm.username"
                            :prefix-icon="User"
                            placeholder="请输入账号"
                            size="large"
                        />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            v-model="loginForm.password"
                            :prefix-icon="Lock"
                            :type="passwordVisible ? 'text' : 'password'"
                            placeholder="请输入密码"
                            size="large"
                        >
                            <template #suffix>
                                <el-icon 
                                    class="cursor-pointer"
                                    @click="passwordVisible = !passwordVisible"
                                >
                                    <View v-if="passwordVisible" />
                                    <Hide v-else />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="captcha">
                        <div class="captcha-container">
                            <el-input
                                v-model="loginForm.captcha"
                                :prefix-icon="Key"
                                placeholder="请输入验证码"
                                size="large"
                            />
                            <div class="captcha-img" @click="refreshCaptcha">
                                <img :src="captchaUrl" alt="验证码" title="点击刷新">
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            :loading="loading"
                            class="login-button"
                            @click="handleLogin"
                        >
                            {{ loading ? '登录中...' : '登 录' }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide, Moon, Sunny, Key } from '@element-plus/icons-vue'
import { useDark, useToggle } from '@vueuse/core'
import {login} from '../api/admin.js'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref(null)

// 暗黑模式
const isDark = useDark()
const toggleDark = useToggle(isDark)

const passwordVisible = ref(false)

// 验证码相关
const captchaUrl = ref('')
const captchaKey = ref('')

// 登录表单增加验证码字段
const loginForm = reactive({
    username: '',
    password: '',
    remember: false,
    captcha: ''
})

// 刷新验证码
const refreshCaptcha = () => {
    // 这里替换为实际的验证码接口
    // 模拟验证码更新
    captchaUrl.value = `https://dummyimage.com/120x40/666/fff.png&text=${Math.random().toString(36).slice(-4)}`
    captchaKey.value = Date.now()
}

// 在组件挂载时检查是否有保存的账号密码
onMounted(() => {
    const savedCredentials = localStorage.getItem('credentials')
    if (savedCredentials) {
        const { username, password } = JSON.parse(savedCredentials)
        loginForm.username = username
        loginForm.password = password
        loginForm.remember = true
    }
    refreshCaptcha()
})

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码长度为4位', trigger: 'blur' }
    ]
}

// 登录处理
const handleLogin = async () => {
    if (!loginFormRef.value) return
    
    await loginFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                
                // 这里应该添加验证码验证逻辑
                // 模拟验证码验证
                if (loginForm.captcha.toLowerCase() !== captchaUrl.value.split('text=')[1].toLowerCase()) {
                    ElMessage.error('验证码错误')
                    refreshCaptcha()
                    return
                }
                const {data:res} =await login('login',loginForm)
                // return console.log(res)
                if (res.data.code ==200) {
                    localStorage.setItem('token', res.data.token)
                    // 如果选择记住密码，保存账号密码
                    if (loginForm.remember) {
                        localStorage.setItem('credentials', JSON.stringify({
                            username: loginForm.username,
                            password: loginForm.password
                        }))
                    } else {
                        localStorage.removeItem('credentials')
                    }

                    localStorage.setItem('user', JSON.stringify({
                        username: loginForm.username,
                        loginTime: new Date().toLocaleString()
                    }))
                    ElMessage.success('登录成功')
                    router.push('/home')
                } else {
                    ElMessage.error('用户名或密码错误')
                    refreshCaptcha()
                }
            } catch (error) {
                console.error('登录失败:', error)
                ElMessage.error('登录失败，请重试')
                refreshCaptcha()
            } finally {
                loading.value = false
            }
        }
    })
}
</script>

<style lang="scss" scoped>
.login-container {
    width: 100%;
    height: 100vh;
    transition: all 0.3s ease;
    
    // 明亮模式下的渐变背景
    background: linear-gradient(45deg, #feac5e, #c779d0, #4bc0c8);
    
    // 暗黑模式下的渐变背景
    &.dark {
        background: linear-gradient(45deg, #2c3e50, #3498db, #2980b9);
        color: var(--el-text-color-primary);
    }
    
    .theme-switch {
        position: absolute;
        top: 20px;
        right: 20px;
        
        .el-button {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            
            &:hover {
                background: rgba(255, 255, 255, 0.3);
            }
        }
    }
    
    .main {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 0 20px;
        box-sizing: border-box;
        
        .name {
            h1 {
                font-size: 38px;
                margin-bottom: 30px;
                color: white;
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
            }
            
            p {
                font-size: 24px;
                color: rgba(255, 255, 255, 0.9);
                text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
            }
        }
        
        .login-card {
            width: 420px;
            height: 580px;
            background: var(--el-bg-color);
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 40px 0;
            display: flex;
            flex-direction: column;
            
            &:hover {
                transform: translateY(-2px);
                transition: all 0.3s ease;
            }
            
            .title {
                text-align: center;
                margin-bottom: 40px;
                
                h2 {
                    font-size: 28px;
                    color: var(--el-text-color-primary);
                    margin-bottom: 20px;
                }
                
                .other {
                    font-size: 14px;
                    color: var(--el-text-color-regular);
                    
                    .el-link {
                        margin-left: 8px;
                    }
                }
            }
            
            .login-form {
                width: 100%;
                padding: 0 40px;
                box-sizing: border-box;
                flex: 1;
                display: flex;
                flex-direction: column;
                
                .el-form-item {
                    margin-bottom: 25px;
                    
                    &:last-child {
                        margin-top: auto;
                        margin-bottom: 20px;
                    }
                }

                :deep(.el-input) {
                    .el-input__wrapper {
                        padding: 4px 15px;
                    }
                    
                    .el-input__inner {
                        height: 40px;
                    }
                }

                :deep(.el-checkbox) {
                    color: var(--el-text-color-regular);
                    margin-bottom: 10px;
                }

                .cursor-pointer {
                    cursor: pointer;
                    color: var(--el-text-color-regular);
                    
                    &:hover {
                        color: var(--el-color-primary);
                    }
                }
                
                .login-button {
                    width: 100%;
                    height: 45px;
                    font-size: 16px;
                    background: linear-gradient(45deg, #feac5e, #c779d0);
                    border: none;
                    border-radius: 4px;
                    font-weight: 500;
                    letter-spacing: 2px;
                    
                    &:hover {
                        background: linear-gradient(45deg, #c779d0, #4bc0c8);
                        transform: translateY(-1px);
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                    }
                    
                    &:active {
                        transform: translateY(0);
                    }
                    
                    .dark & {
                        background: linear-gradient(45deg, #2c3e50, #3498db);
                        
                        &:hover {
                            background: linear-gradient(45deg, #3498db, #2980b9);
                        }
                    }
                }

                .captcha-container {
                    display: flex;
                    gap: 10px;
                    align-items: center;
                    
                    .el-input {
                        flex: 1;
                    }
                    
                    .captcha-img {
                        width: 120px;
                        height: 40px;
                        cursor: pointer;
                        border-radius: 4px;
                        overflow: hidden;
                        
                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                            vertical-align: middle;
                        }
                        
                        &:hover {
                            opacity: 0.8;
                        }
                    }
                }
            }
        }
    }
}

// 响应式布局
@media screen and (max-width: 768px) {
    .login-container {
        .main {
            flex-direction: column;
            padding: 20px;
            
            .name {
                text-align: center;
                margin-bottom: 40px;
                
                h1 {
                    font-size: 28px;
                }
                
                p {
                    font-size: 18px;
                }
            }
            
            .login-card {
                width: 100%;
                max-width: 480px;
            }
        }
    }
}
</style> 